//
//  PlanCtrl.m
//  Traveling
//
//  Created by Northwan on 15/5/12.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "PlanCtrl.h"
#import "DaysRouteInfo.h"
#import "RouteItemCell.h"
#import "RouteDaysView.h"
#import "CustomShowView.h"
#import "RouteTypeSelectView.h"
#import "RouteItemSelectCtrl.h"
#import "SaveTripDialog.h"
#import "CreatRouteInfo.h"
#import "MineDataTool.h"
#import "LoginCtrl.h"
#import "MyTripOrdersCtrl.h"

@interface PlanCtrl ()<UITableViewDataSource,UITableViewDelegate,RouteDaysViewDelegate,RouteItemDelegate,RouteTypeSelectViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *totalLabel;

@property (nonatomic, strong) NSMutableArray *daysArray;

@property (nonatomic ,weak) CustomShowView *showView;

@property (nonatomic, strong) CreatRouteInfo *routeInfo;

@end

@implementation PlanCtrl

-(instancetype)initWithCreatRouteInfo:(CreatRouteInfo *)creatRouteInfo
{
    self = [super init];
    if (self) {
        self.routeInfo = creatRouteInfo;
        self.daysArray = [NSMutableArray arrayWithArray:self.routeInfo.days];
    }
    return self;
}

-(CreatRouteInfo *)routeInfo{
    if (!_routeInfo) {
        _routeInfo = [[CreatRouteInfo alloc] init];
    }
    return _routeInfo;
}

-(NSMutableArray *)daysArray{
    if (!_daysArray) {
        _daysArray = [NSMutableArray array];
    }
    return _daysArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"RouteItemCell" bundle:nil] forCellReuseIdentifier:@"RouteItemCell"];
    self.tableView.tableFooterView = [UIView new];
    if (self.daysArray.count==0) {
        [self addDayBtnClick:nil];
    }else{
        [self.tableView reloadData];
    }
    [Utils setSeparatorInsetWithTableView:self.tableView insets:UIEdgeInsetsMake(0, 8, 0, 8)];
}


- (IBAction)addDayBtnClick:(id)sender {
    if (self.daysArray.count==10) {
        [DialogUtils showTips:@"最多只能增加10天的行程"];
        return;
    }
    DaysRouteInfo *daysRouteInfo = [[DaysRouteInfo alloc] init];
    daysRouteInfo.day_num = self.daysArray.count+1;
    [self.daysArray addObject:daysRouteInfo];
    [self.tableView reloadData];
    [self calcPrice];
}


- (IBAction)savePlanBtnClick:(id)sender {
    NSMutableString *path = [NSMutableString string];
    
    for (int i=0; i<self.daysArray.count; i++) {
        DaysRouteInfo *daysRouteInfo = self.daysArray[i];
        if (daysRouteInfo.items.count==0) {
            [path appendFormat:@"第%ld天，",daysRouteInfo.day_num];
        }
    }
    if (path.length>0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@没有行程项目。请选择",path] delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    SaveTripDialog *dialog = [SaveTripDialog tripDialogWithName:self.routeInfo.plan_name dateStr:self.routeInfo.plan_start result:^(NSString *name, NSString *dateStr) {
        self.routeInfo.days = self.daysArray;
        self.routeInfo.plan_name = name;
        self.routeInfo.plan_start = dateStr;
        [self commitData];
        [self.showView hideWithanim:YES];
        self.showView = nil;
    }];
    dialog.width = SCREENW-16;
    CustomShowView *showView = [[CustomShowView alloc] initWithCustomView:dialog];
    [showView setBackgroundColor:RGBAColor(0, 0, 0, 0.3)];
    self.showView = showView;
    [self.showView showWithanim:YES];
}

-(void)commitData{
    //去提交服务器
    if (isLogin) {
        NSString *json_plan = [NSString paramStringWithPram:[self.routeInfo keyValues]];
        NSLog(@"json_plan＝%@",json_plan);
        [DialogUtils showLoding];
        [MineDataTool createTripOrderUserId:[DefaultsHelper stringForKey:kUserId] json_plan:json_plan success:^(BaseResponse *result) {
            [DialogUtils hideLoding];
            if (result.isSucc) {
                [self resetData];
                if (ISBLANK(self.routeInfo.plan_id)) {
                    [self.navigationController pushViewController:[[MyTripOrdersCtrl alloc] init] animated:YES];
                }else{
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else{
                [DialogUtils showTips:result.msg];
            }
        } failure:^(NSError *error) {
            [DialogUtils hideLoding];
            [DialogUtils showTips:@"提交失败"];
        }];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"请登录后进行保存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

/**
 *  重置数据
 */
-(void)resetData{
    self.daysArray = nil;
    self.routeInfo = nil;
    [self addDayBtnClick:nil];
    [self.tableView reloadData];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        NSLog(@"确定");
        [self.navigationController pushViewController:[[LoginCtrl alloc] init ]animated:YES];
    }
}

#pragma mark - tableView delegate&datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.daysArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    DaysRouteInfo *daysRouteInfo = self.daysArray[section];
    return daysRouteInfo.items.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RouteItemCell *cell = [RouteItemCell cellWithTableView:tableView section:indexPath.section];
    cell.delegate = self;
    ItemRouteInfo *itemRouteInfo = [self.daysArray[indexPath.section] items][indexPath.row];
    [cell setItemRouteInfo:itemRouteInfo];
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RouteDaysView *daysView = [RouteDaysView daysView];
    daysView.delegate = self;
    [daysView setDayNum:section+1];
    return daysView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}


#pragma mark - RouteDaysViewDelegate

-(void)routeDaysViewDeleteWithDayNum:(NSInteger)dayNum{
    [self.daysArray removeObjectAtIndex:dayNum-1];
    for (int i=0; i<self.daysArray.count; i++) {
        DaysRouteInfo *routeInfo = self.daysArray[i];
        routeInfo.day_num = i+1;
    }
    //重新计算price
    [self calcPrice];
    [self.tableView reloadData];
}

-(void)routeDaysViewAddItemWithDayNum:(NSInteger)dayNum addBtn:(UIButton *)button{
    RouteTypeSelectView *selectView = [RouteTypeSelectView selectView];
    selectView.tag = dayNum-1;
    selectView.delegate = self;
    //获取button在屏幕 上的位置
    CGRect rect = [button.superview convertRect:button.frame toView:nil];
    CustomShowView *showView = [[CustomShowView alloc] initWithCustomView:selectView leftTopPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)+10)];
    [showView showWithanim:YES];
    self.showView = showView;
}

#pragma mark - RouteItemDelegate 行程条目cell点击删除按钮回调
-(void)routeItemCellDeleteWithSection:(NSInteger)section itemRouteInfo:(ItemRouteInfo *)itemRouteInfo{
    DaysRouteInfo *routeInfo = self.daysArray[section];
    [routeInfo.items removeObject:itemRouteInfo];
    for (int i=0; i<routeInfo.items.count; i++) {
        ItemRouteInfo *item = routeInfo.items[i];
        item.sort = i;
    }
    //重新计算price
    [self calcPrice];
    [self.tableView reloadData];

}
#pragma mark - RouteTypeSelectViewDelegate 选择景点还是酒店的回调
-(void)routeTypeSelectWithType:(RouteType)type index:(NSInteger)index{
    NSLog(@"%d",type);
    [self.showView hideWithanim:YES];
    RouteItemSelectCtrl *ctrl = [[RouteItemSelectCtrl alloc] initWithRouteType:type result:^(ItemRouteInfo *routeInfo) {
        DaysRouteInfo *daysRouteInfo = self.daysArray[index];
        //判断是否存在
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@",routeInfo.item_id];
        if ([daysRouteInfo.items filteredArrayUsingPredicate:predicate].count>0) {
            [DialogUtils showTips:[NSString stringWithFormat:@"在第%ld天内已存在",index+1]];
            return;
        }
        routeInfo.sort = daysRouteInfo.items.count;
        [daysRouteInfo.items addObject:routeInfo];
        //重新计算price
        [self calcPrice];
        [self.tableView reloadData];
    }];
    [self.navigationController pushViewController:ctrl animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    [Utils setSeparatorInsetWithTableViewCell:cell insets:UIEdgeInsetsMake(0, 8, 0, 8)];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView){
        CGFloat sectionHeaderHeight = 50;
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

-(void)calcPrice{
    CGFloat price = 0.0;
    NSInteger count = 0;
//    NSString *sum= [self.daysArray valueForKeyPath:@"items.@sum.price"];
//    NSLog(@"sum = %@",sum);
    for (int i=0; i<self.daysArray.count; i++) {
        DaysRouteInfo *daysRouteInfo = self.daysArray[i];
        price +=[[daysRouteInfo valueForKeyPath:@"items.@sum.price"] doubleValue];
        count +=daysRouteInfo.items.count;
    }
    self.routeInfo.plan_price = price;
    [self.totalLabel setText:[NSString stringWithFormat:@"%ld个项目，共计%.2f元",count,price]];
}

@end
